<?php
/**
 * @copyright: ©2024 永州 微聚商网络科技有限公司
 * @link: https://www.wEijuyunke.com
 */

namespace app\mobile\controller;

use AlibabaCloud\SDK\ICE\V20201109\Models\SubmitDNAJobRequest\input;
use app\admin\model\AgentAvatar;
use app\admin\model\AgentCompositeAvatar;
use app\admin\model\AgentInfo;
use app\admin\model\AgentUser;
use app\admin\model\ClipProject;
use app\admin\model\ClipVideoRepost;
use app\admin\model\FigureAicreate;
use app\admin\model\FigureAiTitle;
use app\admin\model\FigureBrokerage;
use app\admin\model\FigureCompositeSound;
use app\admin\model\FigureThreePartiesAccount;
use app\admin\model\HomepageVideo;
use app\admin\model\IntelligenceLog;
use app\admin\model\RepostComment;
use app\admin\model\template\GenerateFail;
use app\admin\model\template\GenerateSuccess;
use app\admin\model\template\Task;
use app\admin\model\ThreeComment;
use app\admin\model\ThreeCopywriting;
use app\admin\model\ThreeTitle;
use app\admin\model\ThreeVideoReleaseTask;
use app\admin\model\ThreeVideoTask;
use app\BaseController;
use app\common\service\AgentApiService;
use app\common\service\KuaishouService;
use OSS\OssClient;
use function Symfony\Component\VarDumper\Tests\Fixtures\bar;
use think\App;
use think\facade\Log;
use app\admin\model\FigureUser;
use app\common\service\ApiService;
use app\admin\model\FigureAvatar;
use app\admin\model\FigureVideo;
use app\admin\model\FigureFaceSwapTask;
use app\admin\model\FigureVoiceTwin;
use app\admin\model\FigureCloneSet;
use app\admin\model\FigureDyUser;
use app\admin\model\FigureKsUser;
use app\admin\model\FigureScreenLog;
use app\admin\model\FigureCompositeAvatar;

use app\admin\model\FigureBrokerageSet;
use app\admin\model\FigureDistribution;
use app\admin\model\FigureMemberLog;
use app\admin\model\FigurePointLog;
use app\admin\model\FigureShareholderLog;

/**
 * 定时任务操作
 *
 * @author Administrator
 *
 */
class Timer extends BaseController
{

    /**
     * 声音克隆定时任务
     * http://aigc.weijuyunke.cn/mobile/timer/voiceTimer
     */
    public function voiceTimer()
    {
        try {
            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();
            } else {
                $apiService = new ApiService();
            }
            $voice = FigureVoiceTwin::where(['current_status' =>'sent'])->select();
            foreach ($voice as $value){
                $result = $apiService->voiceDetail(['id' =>$value['_id']]);
                if (isset($result['code'] )&& $result['code'] ==1 ){
                    if (isset($result['data'] ) && $result['data']){
                        if ($result['data']['current_status'] != $value['current_status']){
                            FigureVoiceTwin::where("id", $value['id'])->save([
                                'current_status' => $result['data']['current_status']
                            ]);
                        }
                    }else{
                        FigureVoiceTwin::where("id", $value['id'])->save([
                            'current_status' => 'failed'
                        ]);
                    }
                }
            }

         /*  $result = $apiService->voiceList();

            if (isset($result['code']) && $result['code'] == 1) {

                if (isset($result['data']) && !empty($result['data'])) {

                    $resultData = $result['data'];
                    foreach ($resultData as $kk => $vv) {
                        $voice = FigureVoiceTwin::where("_id", $vv['id'])->find();
                        if ($voice) {
                            FigureVoiceTwin::where("_id", $vv['id'])->save([
                                'current_status' => $vv['current_status']
                            ]);
                        }
                    }
                }
            } else {
                return result(-1, $result['msg']);
            }

           ;*/
         echo '声音克隆定时任务执行完成<br>';
        } catch (\Exception $e) {
            Log::error("Timer  voiceTimer:异常" . $e->getMessage() . "+++" . $e->getLine());
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 高级形象克隆定时任务
     * http://aigc.weijuyunke.cn/mobile/timer/avatarTimer
     */
   /* public function avatarTimer()
    {
        try {

            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();
            } else {
                $apiService = new ApiService();
            }
            $result = $apiService->avatarList();

            if (isset($result['code']) && $result['code'] == 1) {

                if (isset($result['data']) && !empty($result['data'])) {

                    $resultData = $result['data'];

                    foreach ($resultData as $kk => $vv) {
                        FigureAvatar::where("_id", $vv['id'])->save([
                            'current_status' => $vv['current_status'],
                            'new_current_status' => $vv['new_current_status'],
                            'composite_current_status' => $vv['composite_current_status'],
                            'four_current_status' => $vv['four_current_status']
                        ]);
                    }
                }
            } else {
                return result(-1, $result['msg']);
            }

            echo '高级形象克隆定时任务执行完成<br>';
        } catch (\Exception $e) {
            Log::error("Timer  avatarTimer:异常" . $e->getMessage() . "+++" . $e->getLine());
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }*/


    /**
     * DY发布视频回调
     * http://aigc.weijuyunke.cn/mobile/timer/hooksNotify
     */
    public function hooksNotify()
    {
        $testxml = file_get_contents("php://input");
        try {
            $encrypt_result = json_decode($testxml, true);
            if ($encrypt_result) {
                $event = $encrypt_result['event'];
                switch ($event) {
                    case 'create_video':
                        $content = $encrypt_result['content'];
                        Log::error("hooksNotify 错误:  " . json_encode($content));
                        $share_id = $content['share_id'];
                        $item_id = $content['item_id'];

                        $row = ClipVideoRepost::where("share_id", $share_id)->find();
                        $ClipProject = new ClipProject();
                        $ClipProject->where('id', $row['video_id'])->update(['is_douyin' => 3]);

                        if (!empty($row)) {
                            ClipVideoRepost::where("share_id", $share_id)->save([
                                "item_id" => $item_id,
                                "dy_video_id" => $content['video_id'],
                                "is_repost" => 1
                            ]);
                        }

                        break;
                    default:
                        if (!empty($encrypt_result['content']['challenge'])) {
                            return json_encode([
                                "challenge" => $encrypt_result['content']['challenge']
                            ]);
                        }
                        break;
                }
            }
        } catch (\Exception $th) {
            Log::error("D音事件回调失败! error: " . $th->getMessage());
        }
    }

    /**
     * 获取DY转发数据定时任务
     * http://aigc.weijuyunke.cn/mobile/timer/dyDataTimer
     */
    public function dyDataTimer()
    {
        try {

            $forwardSet = sysconfig('forward');

            // if (isset($forwardSet['d_video_data']) && $forwardSet['d_video_data'] == 1) {
            $list = ClipVideoRepost::where(" is_repost  = 1 AND way = 1 ")->order('create_time', 'asc')->select();
            foreach ($list as $key => $value) {
                if (sysconfig('account', 'operation_version') == 2) {
                    $apiService = new AgentApiService();
                } else {
                    $apiService = new ApiService();
                }
                $douyinVideoInfo = $apiService->douyinVideoInfo([
                    'aweme_id' => $value['dy_video_id'],
                ]);
                if ($douyinVideoInfo['data']['status_code'] == 0 && isset($douyinVideoInfo['data']['aweme_detail'])) {
                    ClipVideoRepost::where(['id' => $value['id']])
                        ->update([
                            'total_comment' => $douyinVideoInfo['data']['aweme_detail']['statistics']['comment_count'],
                            'total_like' => $douyinVideoInfo['data']['aweme_detail']['statistics']['digg_count'],
                            'total_play' => $douyinVideoInfo['data']['aweme_detail']['statistics']['play_count'],
                            'total_share' =>    $douyinVideoInfo['data']['aweme_detail']['statistics']['share_count'],
                            'share_url' =>     $douyinVideoInfo['data']['aweme_detail']['share_url'],
                        ]);

                }


                /*    $user = FigureDyUser::where('id', $value['d_uid'])->find();

                    $encode_item_id = urlencode($value['item_id']);

                    $url = "https://open.douyin.com/api/douyin/v1/video/video_data/?open_id=" . $user['openid'] . "&item_id=" . $encode_item_id;
                    $item_ids[] =['item_ids'=> $encode_item_id];
                    $item_ids =json_encode($item_ids, true);
                    $arr = $this->forward_video_request($url, $item_ids, $user['access_token']);
                    $arr1 = json_decode($arr, true);
                    if ($arr1){
                        if ($arr1['data']['error_code'] == 0) {
                            if (array_key_exists("result", $arr1['data']) && !empty($arr1['data']['result'])) {
                                $arr_data = $arr1['data']["result"];

                                $total_comment = $arr_data['total_comment'];
                                $total_like = $arr_data['total_like'];
                                $total_share = $arr_data['total_share'];
                                $total_play = $arr_data['total_play'];
                                $data = array(
                                    'total_comment' => $total_comment,
                                    'total_like' => $total_like,
                                    'total_play' => $total_play,
                                    'total_share' => $total_share,
                                    'share_url' => $value["video_url"]
                                );
                                ClipVideoRepost::where("item_id", $value['item_id'])->update($data);
                            }
                        }

                        $commentUrl = "https://open.douyin.com/api/apps/v1/item/get_comment/?open_id=" . $user['openid'] . "&item_id=" . $encode_item_id.'&date_type=7';

                        $commentArr = $this->forward_video_request($commentUrl, [], $user['access_token']);
                        $commentArr1 = json_decode($commentArr, true);
                        if ($commentArr1['data']['error_code'] == 0) {
                            foreach ($commentArr1['data']['data'] as  $commenValue){
                                $RepostCommentModel =  new RepostComment();
                                 $RepostCommentInfo  =  $RepostCommentModel->where([
                                      'comment_id' =>$commenValue['id'],
                                      'repost_id' => $value['id'],
                                  ])->find();
                                if (empty($RepostCommentInfo)){
                                    $commentData =[
                                        'repost_id' => $value['id'],
                                        'user_name' => $value['id'],
                                        'user_avater' => $value['id'],
                                        'comment' => $value['id'],
                                        'comment_id' => $value['id'],
                                        'partent_comment_id' => $value['id'],
                                        'way' => 1

                                    ];

                                }

                            }
                        }
                    }*/



            }
            // }

            echo '获取DY转发数据定时任务执行完成<br>';
      } catch (\Exception $e) {
            Log::error("Timer  dyDataTimer:异常" . $e->getMessage() . "+++" . $e->getLine());
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 获取KS转发数据定时任务
     * http://aigc.weijuyunke.cn/mobile/timer/ksDataTimer
     */
    public function ksDataTimer()
    {
        try {

            $list = ClipVideoRepost::where(" is_repost  = 1 AND way = 2 ")->order('create_time', 'asc')->select();

            $forwardSet = sysconfig('forward');

            $k_appid = $forwardSet['k_appid'];
            $k_secret = $forwardSet['k_secret'];

            foreach ($list as $key => $value) {

                $user = FigureKsUser::where('id', $value['k_uid'])->find();

                $url = "https://open.kuaishou.com/openapi/photo/list?access_token=" . $user['access_token'] . "&app_id=" . $k_appid;
                $arr = httpGet($url);
                $arr1 = json_decode($arr, true);


                $result = $arr1["result"];

                if ($result == "1") {
                    $video_list = $arr1["video_list"];
                    foreach ($video_list as $k => $v) {
                        $total_comment = $v["comment_count"];
                        $total_like = $v["like_count"];
                        $total_play = $v["view_count"];

                        $data = array();
                        if (!empty($total_comment)) {
                            $data['total_comment'] = $total_comment;
                        }
                        if (!empty($total_like)) {
                            $data['total_like'] = $total_like;
                        }
                        if (!empty($total_play)) {
                            $data['total_play'] = $total_play;
                        }

                        $data["share_url"] = $v["play_url"];

                        ClipVideoRepost::where("photo_id", $v["photo_id"])->update($data);
                    }
                }
            }

            echo '获取KS转发数据定时任务执行完成<br>';
        } catch (\Exception $e) {
            Log::error("Timer  ksDataTimer:异常" . $e->getMessage() . "+++" . $e->getLine());
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 视频下载后到期删除定时任务
     * http://aigc.weijuyunke.cn/mobile/timer/videoDelTimer
     */
    public function videoDelTimer()
    {
        try {

            $set = FigureCloneSet::where('id', 1)->find();

            $list = FigureVideo::where(" local_url != '' ")->order('create_time', 'asc')->select();

            foreach ($list as $key => $value) {

                $newTime = strtotime("+{$set['video_expire']} day", strtotime($value['local_time']));

                if (time() > $newTime) {

                    $urlTemp = explode("/", $value['local_url']);
                    $urlName = end($urlTemp);

                    $coverTemp = explode("/", $value['local_cover']);
                    $coverName = end($coverTemp);

                    $url_path = root_path() . 'public/uploads/video/' . $urlName;
                    $cover_path = root_path() . 'public/uploads/video-cover/' . $coverName;

                    if (is_file($url_path)) {
                        unlink($url_path);
                    }
                    if (is_file($cover_path)) {
                        unlink($cover_path);
                    }

                    $row = FigureVideo::where('id', $value['id'])->find();
                    $row->delete();
                }
            }

            echo '视频下载后到期删除定时任务执行完成<br>';
        } catch (\Exception $e) {
            Log::error("Timer  videoDelTimer:异常" . $e->getMessage() . "+++" . $e->getLine());
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 视频剪辑定时任务
     * http://aigc.weijuyunke.cn/mobile/timer/videoTimer
     */
    public function videoTimer()
    {
        /*  try {*/

        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }

        $FigureVideoList = FigureVideo::where("current_status", 'init')->select();

        foreach ($FigureVideoList as  $value){
            $result = $apiService->awsDetail(['id' =>  $value['_id']]);
            if (isset($result['code'] )&& $result['code'] ==1 ){
                if (isset($result['data'] ) && $result['data']){
                    if ($result['data']['current_status'] == 'oss_init'){
                        continue;
                    }
                    if ($result['data']['current_status'] != $value['current_status']){
                        FigureVideo::where("id", $value['id'])->save([
                            'current_status' => $result['data']['current_status'],
                            'result' => !empty($result['data']['result']) ? $result['data']['result'] : '',
                            'result_cover' => !empty($result['data']['result_cover']) ? $result['data']['result_cover'] : ''

                        ]);

                        if ($result['data']['current_status'] == 'success') {
                            if ($value['is_batch_generate'] == 1 && $value['current_status'] == 'init') {
                                $batchGenerateList = FigureVideo::where("log_no", $value['log_no'])->select();
                                $isSend = 1;
                                $successCount = 0;
                                $failCount = 0;
                                foreach ($batchGenerateList as $batchGenerateListValue) {
                                    if ($batchGenerateListValue['current_status'] == 'wait_sent' || $batchGenerateListValue['current_status'] == 'init') {
                                        $isSend = 0;
                                        if ($batchGenerateListValue['current_status'] == 'success') {
                                            $successCount++;
                                        }
                                        if ($batchGenerateListValue['current_status'] == 'fail') {
                                            $failCount++;
                                        }

                                    }
                                }
                                if ($isSend == 1) {
                                    $userModel = new FigureUser();
                                    $userInfo = $userModel->where(['id' => $value['uid']])->find();
                                    $generateData ['openid'] = $userInfo['openid'];
                                    $generateData['thing14'] = $value['name'];
                                    $generateData['thing4'] = '成功' . $successCount . ',失败' . $failCount;
                                    $generateData['date3'] = date('Y-m-d H:i', time());
                                    $generateSuccess = new Task($generateData);
                                    $generateSuccess->send();
                                }
                            } else {
                                if ($value['current_status'] == 'init') {
                                    $userModel = new FigureUser();
                                    $userInfo = $userModel->where(['id' => $value['uid']])->find();
                                    $generateData ['openid'] = $userInfo['openid'];
                                    $generateData['thing1'] = $value['name'];
                                    $generateData['time2'] = date('Y-m-d H:i', time());
                                    $generateData['thing3'] = '视频合成生成';
                                    $generateSuccess = new GenerateSuccess($generateData);

                                    $generateSuccess->send();
                                }

                            }

                        }

                        if ($result['data']['current_status'] == 'fail') {
                            if ($value['is_batch_generate'] == 1 && $value['current_status'] == 'init') {
                                $batchGenerateList = FigureVideo::where("log_no", $value['log_no'])->select();
                                $isSend = 1;
                                $successCount = 0;
                                $failCount = 0;
                                foreach ($batchGenerateList as $batchGenerateListValue) {
                                    if ($batchGenerateListValue['current_status'] == 'wait_sent' || $batchGenerateListValue['current_status'] == 'init') {
                                        $isSend = 0;
                                        if ($batchGenerateListValue['current_status'] == 'success') {
                                            $successCount++;
                                        }
                                        if ($batchGenerateListValue['current_status'] == 'fail') {
                                            $failCount++;
                                        }

                                    }
                                }
                                if ($isSend == 1) {
                                    $userModel = new FigureUser();
                                    $userInfo = $userModel->where(['id' => $value['uid']])->find();
                                    $generateData ['openid'] = $userInfo['openid'];
                                    $generateData['thing14'] = $value['name'];
                                    $generateData['thing4'] = '成功' . $successCount . ',失败' . $failCount;
                                    $generateData['date3'] = date('Y-m-d H:i', time());
                                    $generateSuccess = new Task($generateData);
                                    $generateSuccess->send();
                                }
                            } else {
                                if ($value['current_status'] == 'init') {
                                    $userModel = new FigureUser();
                                    $userInfo = $userModel->where(['id' => $value['uid']])->find();
                                    $generateData ['openid'] = $userInfo['openid'];
                                    $generateData['thing1'] = $value['name'];
                                    $generateData['time2'] = date('Y-m-d H:i', time());
                                    $generateData['thing3'] = '视频合成生成';
                                    $generateSuccess = new GenerateFail($generateData);
                                    $generateSuccess->send();
                                }

                            }

                        }
                    }


                }else{
                    FigureVoiceTwin::where("id", $value['id'])->save([
                        'current_status' => 'failed'
                    ]);
                }
            }
        }



     /*   $result = $apiService->videoList();
        if (isset($result['code']) && $result['code'] == 1) {

            if (isset($result['data']) && !empty($result['data'])) {

                $resultData = $result['data'];

                foreach ($resultData as $kk => $vv) {
                    $FigureVideoInfo = FigureVideo::where("_id", $vv['id'])->find();
                    if ($FigureVideoInfo) {
                        FigureVideo::where("_id", $vv['id'])->save([
                            'current_status' => $vv['current_status'],
                            'result' => !empty($vv['customer_video_url']) ? $vv['customer_video_url'] : $vv['result'],
                            'result_cover' => !empty($vv['customer_cover']) ? $vv['customer_cover'] : $vv['result_cover']

                        ]);
                        if ($vv['current_status'] == 'success') {
                            if ($FigureVideoInfo['is_batch_generate'] == 1 && $FigureVideoInfo['current_status'] == 'init') {
                                $batchGenerateList = FigureVideo::where("log_no", $FigureVideoInfo['log_no'])->select();
                                $isSend = 1;
                                $successCount = 0;
                                $failCount = 0;
                                foreach ($batchGenerateList as $value) {
                                    if ($value['current_status'] == 'wait_sent' || $value['current_status'] == 'init') {
                                        $isSend = 0;
                                        if ($value['current_status'] == 'success') {
                                            $successCount++;
                                        }
                                        if ($value['current_status'] == 'fail') {
                                            $failCount++;
                                        }

                                    }
                                }
                                if ($isSend == 1) {
                                    $userModel = new FigureUser();
                                    $userInfo = $userModel->where(['id' => $FigureVideoInfo['uid']])->find();
                                    $generateData ['openid'] = $userInfo['openid'];
                                    $generateData['thing14'] = $FigureVideoInfo['name'];
                                    $generateData['thing4'] = '成功' . $successCount . ',失败' . $failCount;
                                    $generateData['date3'] = date('Y-m-d H:i', time());
                                    $generateSuccess = new Task($generateData);
                                    $generateSuccess->send();
                                }
                            } else {
                                if ($FigureVideoInfo['current_status'] == 'init') {
                                    $userModel = new FigureUser();
                                    $userInfo = $userModel->where(['id' => $FigureVideoInfo['uid']])->find();
                                    $generateData ['openid'] = $userInfo['openid'];
                                    $generateData['thing1'] = $FigureVideoInfo['name'];
                                    $generateData['time2'] = date('Y-m-d H:i', time());
                                    $generateData['thing3'] = '视频合成生成';
                                    $generateSuccess = new GenerateSuccess($generateData);

                                    $generateSuccess->send();
                                }

                            }

                        }

                        if ($vv['current_status'] == 'fail') {
                            if ($FigureVideoInfo['is_batch_generate'] == 1 && $FigureVideoInfo['current_status'] == 'init') {
                                $batchGenerateList = FigureVideo::where("log_no", $FigureVideoInfo['log_no'])->select();
                                $isSend = 1;
                                $successCount = 0;
                                $failCount = 0;
                                foreach ($batchGenerateList as $value) {
                                    if ($value['current_status'] == 'wait_sent' || $value['current_status'] == 'init') {
                                        $isSend = 0;
                                        if ($value['current_status'] == 'success') {
                                            $successCount++;
                                        }
                                        if ($value['current_status'] == 'fail') {
                                            $failCount++;
                                        }

                                    }
                                }
                                if ($isSend == 1) {
                                    $userModel = new FigureUser();
                                    $userInfo = $userModel->where(['id' => $FigureVideoInfo['uid']])->find();
                                    $generateData ['openid'] = $userInfo['openid'];
                                    $generateData['thing14'] = $FigureVideoInfo['name'];
                                    $generateData['thing4'] = '成功' . $successCount . ',失败' . $failCount;
                                    $generateData['date3'] = date('Y-m-d H:i', time());
                                    $generateSuccess = new Task($generateData);
                                    $generateSuccess->send();
                                }
                            } else {
                                if ($FigureVideoInfo['current_status'] == 'init') {
                                    $userModel = new FigureUser();
                                    $userInfo = $userModel->where(['id' => $FigureVideoInfo['uid']])->find();
                                    $generateData ['openid'] = $userInfo['openid'];
                                    $generateData['thing1'] = $FigureVideoInfo['name'];
                                    $generateData['time2'] = date('Y-m-d H:i', time());
                                    $generateData['thing3'] = '视频合成生成';
                                    $generateSuccess = new GenerateFail($generateData);
                                    $generateSuccess->send();
                                }

                            }

                        }

                        FigureScreenLog::where("_id", $vv['id'])->save([
                            'current_status' => $vv['current_status'],
                            'result' => $vv['result']
                        ]);
                    }


                }
            }
        } else {
            return result(-1, $result['msg']);
        }*/

        echo '视频剪辑定时任务执行完成<br>';
        /* } catch (\Exception $e) {
             Log::error("Timer  faceTimer:异常" . $e->getMessage() . "+++" . $e->getLine());
             return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
             exit();
         }*/
    }

    function forward_video_request($url, $data = null, $token = null)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        if ($data != null) {
            curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        }

        $header = array(
            'Content-Type: application/json'
        );

        if ($token != null) {
            array_push($header, 'access-token:  ' . $token);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // 类型为json
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, 300); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $info = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            // echo 'Errno:'.curl_getinfo($curl);//捕抓异常
            // dump(curl_getinfo($curl));
        }

        return $info;
    }

    public function getTransfer()
    {
        $FigureBrokerageModel = new FigureBrokerage();
        $FigureBrokerageList = $FigureBrokerageModel->where(['is_status' => 1])->select();
        foreach ($FigureBrokerageList as $value) {
            $result = getTransfer($value['log_no']);

            if ($result['code'] == 1 && $result['data']['state'] == 'SUCCESS') {
                $FigureBrokerageModel->where(['log_no' => $value['log_no']])->update(['is_status' => 2]);
            }

        }

    }

    public function test()
    {

        var_dump(require_once(app()->getRootPath() . "config/upgrade/sql/upgrade.php"));
    }


//http://aigc.weijuyunke.cn/mobile/timer/shareholder
    public function shareholder()
    {

        $set = FigureBrokerageSet::where("id", 1)->find();
        if ($set['is_shareholder_swich'] == 2) {
            return '股东关闭';
        }
        $distributionModel = new FigureDistribution();
        $distributionList = $distributionModel->where(['is_shareholder_swich' => 1])->select()->toArray();

        if (empty($distributionList)) {
            echo '无执行数据';
            exit;
        }
        $distributionId = [];
        foreach ($distributionList as $value) {
            $distributionId[] = $value['id'];
        }
        $figureUserModel = new FigureUser();
        $userList = $figureUserModel->where('distribution_level_id', 'in', $distributionId)->select()->toArray();
        if (empty($userList)) {
            echo '无执行数据';
            exit;
        }

        $now = time();
        $todayMidnight = strtotime('today', $now);
        $yesterdayMidnight = $todayMidnight - 86400;
        $setting = FigureBrokerageSet::where('id', 1)->find();
        if ($setting['shareholder_radio'] > 0) {
            $memberLogCount = FigureMemberLog::where(['pay_status' => 2])
                ->where('create_time', '>=', $yesterdayMidnight)
                ->where('create_time', '<', $now)
                ->sum('money');
            $pointLogCount = FigurePointLog::where(['pay_status' => 2])
                ->where('create_time', '>=', $yesterdayMidnight)
                ->where('create_time', '<', $now)
                ->sum('money');
            $userCount = count($userList);
            $totalMoney = bcadd($memberLogCount, $pointLogCount, 2);
            $shareholderTotalMoney = bcdiv(bcmul($totalMoney, $setting['shareholder_radio'], 2), '100', 2);
            $everyShareholderMoney = bcdiv($shareholderTotalMoney, $userCount, 2);
            $ShareholderLogModel = new FigureShareholderLog();
            foreach ($userList as $userValue) {
                $yesterday = date('Y-m-d', $yesterdayMidnight);
                $ShareholderLog = $ShareholderLogModel->where(['amount_time' => $yesterdayMidnight, 'uid' => $userValue['id']])->find();
                if ($ShareholderLog) {
                    continue;
                }
                $shareholderLog = [
                    'uid' => $userValue['id'],
                    'total' => $totalMoney,
                    'money' => $everyShareholderMoney,
                    'distribution_level' => $userValue['distribution_level'],
                    'distribution_level_id' => $userValue['distribution_level_id'],
                    'shareholder_radio' => $setting['shareholder_radio'],
                    'create_time' => time(),
                    'shareholder_number' => $userCount,
                    'amount_time' => $yesterdayMidnight
                ];
                $ShareholderLogModel->insert($shareholderLog);
                $figureUserModel->where(['id' => $userValue['id']])->inc('brokerage', $everyShareholderMoney)->update();
            }
        }

    }


    public function compositeMigrate()
    {
        $FigureCompositeAvatarModel = new FigureCompositeAvatar();
        $FigureAvatarModel = new FigureAvatar();

        for ($i = 0; $i < 100; $i++) {
            $data = [];
            $number = 100;
            $start = $i * $number;
            $FigureCompositeAvatarList = $FigureCompositeAvatarModel->where(['current_status' => 'completed'])->limit($start, $number)->select();

            if (empty($FigureCompositeAvatarList)) {
                break;
            }
            foreach ($FigureCompositeAvatarList as $value) {
                $FigureVideoTwinInfo = $FigureAvatarModel->where(['composite_id' => $value['id']])->find();
                if (empty($FigureVideoTwinInfo)) {
                    $data[] = [
                        'uid' => $value['uid'],
                        'name' => $value['name'],
                        'video_url' => $value['url'],
                        'composite_id' => $value['id'],
                        'create_time' => strtotime($value['create_time']),
                        'update_time' => strtotime($value['update_time']),
                        'ascription_type' => $value['ascription_type'],
                        'order_id' => $value['order_id'],
                        'is_share' => $value['is_share'],
                        'log_no' => $value['log_no'],
                        'video_cover' => $value['url'] . '?x-oss-process=video/snapshot,t_0,f_jpg,w_0,h_0,m_fast,ar_auto'
                    ];
                }
            }
            if ($data) {
                $FigureAvatarModel->insertAll($data);
            }
        }
    }

    public function agentCompositeMigrate()
    {
        $FigureCompositeAvatarModel = new AgentCompositeAvatar();
        $FigureAvatarModel = new AgentAvatar();

        for ($i = 0; $i < 100; $i++) {
            $data = [];
            $number = 100;
            $start = $i * $number;
            $FigureCompositeAvatarList = $FigureCompositeAvatarModel->where(['current_status' => 'completed'])->limit($start, $number)->select();

            if (empty($FigureCompositeAvatarList)) {
                break;
            }
            foreach ($FigureCompositeAvatarList as $value) {
                $FigureVideoTwinInfo = $FigureAvatarModel->where(['composite_id' => $value['id']])->find();
                if (empty($FigureVideoTwinInfo)) {
                    $data[] = [
                        'agent_id' => $value['agent_id'],
                        'name' => $value['name'],
                        'video_url' => $value['url'],
                        'callbackUrl' => $value['callbackUrl'],
                        'composite_id' => $value['id'],
                        'create_time' => strtotime($value['create_time']),
                        'update_time' => strtotime($value['update_time']),


                        'log_no' => $value['log_no'], 'video_cover' => $value['url'] . '?x-oss-process=video/snapshot,t_0,f_jpg,w_0,h_0,m_fast,ar_auto'
                    ];
                }
            }
            if ($data) {
                $FigureAvatarModel->insertAll($data);
            }
        }
    }


    public function getUser()
    {

        $where = [];
        $userModel = new FigureUser();
        $count = $userModel
            ->count();
        $list = $userModel
            ->order('create_time', 'desc')
            ->select();

        return msg([
            'list' => $list,
            'count' => $count
        ], 0, "success");
    }

    public function getAgent()
    {


        return msg([
            'list' => [],
            'count' => 0
        ], 0, "success");
    }

    // /mobile/timer/wordBecomeByte
    public function wordBecomeByte()
    {
        $userModel = new FigureUser();
        $userList = $userModel->where(['is_execute_number' => 0])->select();
        foreach ($userList as $value) {
            $high_fidelity_words_number = $value['high_fidelity_words_number'] * 3;
            $xunfei_sound_generate_words_number = $value['xunfei_sound_generate_words_number'] * 3;
            $userModel->where(['id' => $value['id']])->update([
                'high_fidelity_words_number' => $high_fidelity_words_number,
                'xunfei_sound_generate_words_number' => $xunfei_sound_generate_words_number,
                'is_execute_number' => 1

            ]);
        }
    }

    public function releaseDouyinVideo()
    {
        $ThreeVideoReleaseTask = new ThreeVideoReleaseTask();
        $taskList = $ThreeVideoReleaseTask->where(['channle_type' => 1, 'status' => 1])
            ->where('release_time', '<=', time())
            ->select()->toArray();
        if ($taskList) {
            $taskid = array_column($taskList, 'id', '');
            $ThreeVideoReleaseTask->where('id', 'in', $taskid)->update(['status' => 2]);
        }
        $FigureThreePartiesAccount = new FigureThreePartiesAccount();
        $threeVideoTaskModel = new ThreeVideoTask();
        $ThreeCopywritingModel = new ThreeCopywriting();
        $FigureAicreateModel = new FigureAicreate();
        $ClipProject = new ClipProject();
        foreach ($taskList as $value) {
            try {
                $data = [];
                $accountInfo = $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])->find();
                $data['cookie'] = $accountInfo['cookie'];
                $liuguanResult = getliuguan($accountInfo['province_id'], $accountInfo['city_id']);
                if ($liuguanResult['code'] == 1) {
                    if (sysconfig('account', 'operation_version') == 2) {
                        $apiService = new AgentApiService();
                    } else {
                        $apiService = new ApiService();
                    }
                    $resultUserInfo = $apiService->douyinAuthorizeUserInfo(['cookie' => $accountInfo['cookie']]);
                    if (isset($resultUserInfo['code']) && $resultUserInfo['code'] == 1) {
                        if ($resultUserInfo['data']['status_code'] != 0) { // 账号过期
                            $taskCount = $ThreeVideoReleaseTask
                                ->where(['three_video_task_id' => $value['three_video_task_id']])
                                ->where('status', 'in', [1, 2])->count();
                            if ($taskCount == 0) {
                                $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])
                                    ->dec('released_task')->update();
                            }
                            user_balance_used($value['uid'], $value['log_no'], 3, 18);
                          //  $ClipProject->where(['id' => $value['clip_project_video_id']])->update(['is_douyin' => 1]);
                            $ThreeVideoReleaseTask->where(['id' => $value['id']])->update(['status' => 4,]);
                            $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])->update(['status' => 2]);
                            continue;
                        }
                    } else {
                        $ThreeVideoReleaseTask->where('id', 'in', $taskid)->update(['status' => 1]);
                        continue;
                    }
                    $threeVideoTaskInfo = $threeVideoTaskModel->where(['id' => $value['three_video_task_id']])->find();
                    $data['poiName'] = $threeVideoTaskInfo['poi_address'];
                    $data['poiId'] = $threeVideoTaskInfo['poi'];
                    /*  $ThreeCopywritingList = $ThreeCopywritingModel->where(['three_video_task_id' => $value['three_video_task_id']])->select()->toArray();
                      $ThreeCopywritingCount = count($ThreeCopywritingList);
                      $ThreeCopywritingIndex = mt_rand(0, $ThreeCopywritingCount - 1);
                      $ThreeCopywritingInfo = $ThreeCopywritingList[$ThreeCopywritingIndex];*/
                    $data['proxy'] = $liuguanResult['data']['ip'];
                    $clipProjctInfo = $ClipProject->where(['id' => $value['clip_project_video_id']])->find();
                    $data['uploadPoster'] = $clipProjctInfo['complete_cover'];
                    $data['video'] = $clipProjctInfo['complete_video'];
                    if ($value['ai_title']) {
                        $FigureAiTitleModel = new FigureAiTitle();
                        $FigureAiTitleInfo = $FigureAiTitleModel->where(['id' => $value['ai_title']])->find();
                        $data['description'] = $FigureAiTitleInfo['answer'] . '#' . $FigureAiTitleInfo['challenges'];

                    }

                    $result = $apiService->releaseDouyinVideo($data);
                    if ($result['code'] == 1) {
                        $ThreeVideoReleaseTask->where(['id' => $value['id']])->update([
                            'status' => 3,
                            'item_id' => $result['data']['item_id'],
                            'logid' => $result['data']['extra']['logid'],
                        ]);
                        $taskCount = $ThreeVideoReleaseTask
                            ->where(['three_video_task_id' => $value['three_video_task_id']])
                            ->where('status', 'in', [1, 2, 5, 6, 7])->count();
                        if ($taskCount == 0) {
                            $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])
                                ->inc('published_task')->dec('released_task')->update();
                            $threeVideoTaskModel->where(['id' => $value['three_video_task_id']])->update(['status' => 3]);
                        }
                        $ClipProject->where(['id' => $value['clip_project_video_id']])->update(['is_douyin' => 3]);

                        if ($clipProjctInfo['is_kuaishou'] == 3 &&  $clipProjctInfo['is_shipinghao'] ==3  &&  $clipProjctInfo['is_xiaohongshu'] ==3){
                            $clipProjctInfo->delete();
                        }

                    } else {
                        $taskCount = $ThreeVideoReleaseTask
                            ->where(['three_video_task_id' => $value['three_video_task_id']])
                            ->where('status', 'in', [1, 2])->count();
                        if ($taskCount == 0) {
                            $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])
                                ->dec('released_task')->update();
                        }
                        //$ClipProject->where(['id' => $value['clip_project_video_id']])->update(['is_douyin' => 1]);
                        user_balance_used($value['uid'], $value['log_no'], 3, 18);
                        $ThreeVideoReleaseTask->where(['id' => $value['id']])->update([
                            'status' => 4,
                        ]);
                    }

                } else {
                    $ThreeVideoReleaseTask->where('id', 'in', $taskid)->update(['status' => 1]);
                }
            } catch (\Exception $exception) {
                $ThreeVideoReleaseTask->where('id', 'in', $taskid)->update(['status' => 1]);
            }
        }
        echo '抖音发布成功';

    }

    public function douyinVideoInfo()
    {
        $ThreeVideoReleaseTask = new ThreeVideoReleaseTask();
        $id = input('id');

        $where = ['channle_type' => 1, 'status' => 3];
        if ($id) {
            $where['id'] = $id;
        }
        $three_account_id = input('three_account_id');
        if ($three_account_id) {
            $where['id'] = $three_account_id;
        }
        $taskList = $ThreeVideoReleaseTask->where($where)
            ->select()->toArray();

        $FigureThreePartiesAccount = new FigureThreePartiesAccount();
        $threeVideoTaskModel = new ThreeVideoTask();
        foreach ($taskList as $value) {
            $data = [];
            $accountInfo = $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])->find();
            $data['cookie'] = $accountInfo['cookie'];
            $liuguanResult = getliuguan($accountInfo['province_id'], $accountInfo['city_id']);
            if ($liuguanResult['code'] == 1) {
                if (sysconfig('account', 'operation_version') == 2) {
                    $apiService = new AgentApiService();
                } else {
                    $apiService = new ApiService();
                }
                $douyinVideoInfo = $apiService->douyinVideoInfo([
                    'cookie' => $accountInfo['cookie'],
                    'aweme_id' => $value['item_id'],
                    'proxy' => $liuguanResult['data']['ip'],
                ]);

                if ($douyinVideoInfo['code'] == 1) {
                    if ($douyinVideoInfo['data']['status_code'] == 0 && isset($douyinVideoInfo['data']['aweme_detail'])) {
                        $ThreeVideoReleaseTask->where(['id' => $value['id']])
                            ->update([
                                'comment' => $douyinVideoInfo['data']['aweme_detail']['statistics']['comment_count'],
                                'like_count' => $douyinVideoInfo['data']['aweme_detail']['statistics']['digg_count'],
                              'exposure_count' => $douyinVideoInfo['data']['aweme_detail']['statistics']['digg_count'],
                            ]);

                    }

                }


            } else {

            }
        }
        $taskList = $ThreeVideoReleaseTask->where($where)
            ->select()->toArray();
        return result(0, 'success', $taskList);
        // echo '抖音发布成功';
    }

    public function releaseKuaishouVideo()
    {
        $ThreeVideoReleaseTask = new ThreeVideoReleaseTask();
        $taskList = $ThreeVideoReleaseTask->where(['channle_type' => 2, 'status' => 1])
            ->where('release_time', '<=', time())->select()->toArray();

        if ($taskList) {
            $taskid = array_column($taskList, 'id', '');
            $ThreeVideoReleaseTask->where('id', 'in', $taskid)->update(['status' => 2]);
        }
        $FigureThreePartiesAccount = new FigureThreePartiesAccount();
        $threeVideoTaskModel = new ThreeVideoTask();
        $ThreeCopywritingModel = new ThreeCopywriting();
        $FigureAicreateModel = new FigureAicreate();
        $ClipProject = new ClipProject();
        foreach ($taskList as $value) {
            $data = [];
            $accountInfo = $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])->find();
            $data['access_token'] = $accountInfo['access_token'];
            if ($accountInfo['expires_in'] > time()) {
                $kuaishouService = new KuaishouService();
                $kuiShouInfo = $kuaishouService->kuaishouUserinfo($accountInfo['access_token']);
                if ($kuiShouInfo['code'] == 0) {
                    $taskCount = $ThreeVideoReleaseTask
                        ->where(['three_video_task_id' => $value['three_video_task_id']])
                        ->where('status', 'in', [1, 2])->count();
                    if ($taskCount == 0) {
                        $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])
                            ->dec('released_task')->update();
                    }
                   // $ClipProject->where(['id' => $value['clip_project_video_id']])->update(['is_kuaishou' => 1]);
                    user_balance_used($value['uid'], $value['log_no'], 3, 19);
                    $ThreeVideoReleaseTask->where(['id' => $value['id']])->update(['status' => 4,]);
                    $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])->update(['status' => 2]);
                    continue;
                }
                $data['access_token'] = $accountInfo['access_token'];
            } else {
                if ($accountInfo['refresh_token_expires_in'] < 0) {
                    $taskCount = $ThreeVideoReleaseTask
                        ->where(['three_video_task_id' => $value['three_video_task_id']])
                        ->where('status', 'in', [1, 2])->count();
                    if ($taskCount == 0) {
                        $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])
                            ->dec('released_task')->update();
                    }
                  //  $ClipProject->where(['id' => $value['clip_project_video_id']])->update(['is_kuaishou' => 1]);
                    user_balance_used($value['uid'], $value['log_no'], 3, 19);
                    $ThreeVideoReleaseTask->where(['id' => $value['id']])->update(['status' => 4,]);
                    $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])->update(['status' => 2]);
                    continue;

                }
                $kuaishouService = new KuaishouService();
                $kuiShouInfo = $kuaishouService->kuaishouRefreshToken($accountInfo['refresh_token_expires_in']);
                if ($kuiShouInfo['code'] == 0) {
                    $taskCount = $ThreeVideoReleaseTask
                        ->where(['three_video_task_id' => $value['three_video_task_id']])
                        ->where('status', 'in', [1, 2])->count();
                    if ($taskCount == 0) {
                        $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])
                            ->dec('released_task')->update();
                    }
                  //  $ClipProject->where(['id' => $value['clip_project_video_id']])->update(['is_kuaishou' => 1]);
                    user_balance_used($value['uid'], $value['log_no'], 3, 19);
                    $ThreeVideoReleaseTask->where(['id' => $value['id']])->update(['status' => 4,]);
                    $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])->update(['status' => 2]);
                    continue;

                } else { // 重新授权账号
                    $FigureThreePartiesAccountModel = new FigureThreePartiesAccount();
                    $user = $FigureThreePartiesAccountModel->where('open_id', $kuiShouInfo['open_id'])->find();
                    $threeAccountData = array(
                        'create_time' => $kuiShouInfo['data']['user_info']['name'],
                        'avatar' => $kuiShouInfo['data']['user_info']['head'],
                        'access_token' => $kuiShouInfo['data']['access_token'],
                        'expires_in' => $kuiShouInfo['data']['expires_in'] + time(),
                        'refresh_token' => $kuiShouInfo['data']['refresh_token'],
                    );
                    if ($user) {
                        $FigureThreePartiesAccountModel->where(['id' => $user['id']])->update($threeAccountData);
                    } else {
                        $FigureThreePartiesAccountModel->save($threeAccountData);
                    }
                    $data['access_token'] = $kuiShouInfo['data']['access_token'];
                }
            }
            $data['merchant_product_id'] = $value['merchant_product_id'];
            $data['anchorUrl'] = $value['anchorUrl'];
            $data['anchorTitle'] = $value['anchorTitle'];
            $data['anchorId'] = $value['anchorId'];


            $clipProjctInfo = $ClipProject->where(['id' => $value['clip_project_video_id']])->find();
            $data['complete_cover'] = $clipProjctInfo['complete_cover'];
            $data['complete_video'] = $clipProjctInfo['complete_video'];

            if ($value['ai_title']) {
                $FigureAiTitleModel = new FigureAiTitle();
                $FigureAiTitleInfo = $FigureAiTitleModel->where(['id' => $value['ai_title']])->find();
                $data['caption'] = $FigureAiTitleInfo['answer'];

            }

            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();
            } else {
                $apiService = new ApiService();
            }
            /*  $resultInfo = $apiService->releaseKuaishouVideo();*/
            /* if ($resultInfo['code'] == 1) {*/
            $result = $kuaishouService->releaseKuaishuoVideo($data);
            /*  $ThreeVideoReleaseTask->where(['id' => $value['id']])
                  ->update(['status' => 1]);*/
            /*  }*/
            if ($result['code'] == 1) {
                $ThreeVideoReleaseTask->where(['id' => $value['id']])->update([
                    'status' => 3,
                    'photo_id' => $result['data']['photo_id'],

                ]);
                $taskCount = $ThreeVideoReleaseTask
                    ->where(['three_video_task_id' => $value['three_video_task_id']])
                    ->where('status', 'in', [1, 2, 5, 6, 7])->count();
                if ($taskCount == 0) {
                    $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])
                        ->inc('published_task')->dec('released_task')->update();
                    $threeVideoTaskModel->where(['id' => $value['three_video_task_id']])->update(['status' => 3]);
                }
                $ClipProject->where(['id' => $value['clip_project_video_id']])->update(['is_kuaishou' => 3]);

                if ($clipProjctInfo['is_douyin'] == 3 &&  $clipProjctInfo['is_shipinghao'] ==3  &&  $clipProjctInfo['is_xiaohongshu'] ==3){
                    $clipProjctInfo->delete();
                }
            } else {
                $taskCount = $ThreeVideoReleaseTask
                    ->where(['three_video_task_id' => $value['three_video_task_id']])
                    ->where('status', 'in', [1, 2])->count();
                if ($taskCount == 0) {
                    $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])
                        ->dec('released_task')->update();
                }
         //       $ClipProject->where(['id' => $value['clip_project_video_id']])->update(['is_kuaishou' => 2]);
                user_balance_used($value['uid'], $value['log_no'], 3, 18);
                $ThreeVideoReleaseTask->where(['id' => $value['id']])->update([
                    'status' => 4,
                ]);
            }

        }
        echo '快手发布成功';
    }

    public function KuaishuoVideoInfo()
    {
        $ThreeVideoReleaseTask = new ThreeVideoReleaseTask();

        $id = input('id');
        $where = ['channle_type' => 2, 'status' => 3];
        if ($id) {
            $where['id'] = $id;
        }
        $three_account_id = input('three_account_id');
        if ($three_account_id) {
            $where['id'] = $three_account_id;
        }
        $taskList = $ThreeVideoReleaseTask->where($where)
            ->select()->toArray();
        /*       $taskList = $ThreeVideoReleaseTask->where(['channle_type' => 2, 'status' => 3])
                   ->select()->toArray();*/

        $FigureThreePartiesAccount = new FigureThreePartiesAccount();
        $forwardSet = sysconfig('forward');
        $k_appid = $forwardSet['k_appid'];
        foreach ($taskList as $value) {
            $accountInfo = $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])->find();
            $url = "https://open.kuaishou.com/openapi/photo/info?access_token=" . $accountInfo['access_token'] . "&app_id=" . $k_appid . '&photo_id=' . $value["photo_id"];
            $arr = httpGet($url);
            $arr1 = json_decode($arr, true);
            if ($arr1['result'] == 1) {
                /*   $videoInfo = $ThreeVideoReleaseTask->where("photo_id", $value["photo_id"])->find();*/

                if ($value['is_hang'] == 1 && $value['anchorUrl']) {
                    $bindData = [
                        'photo_id' => $value["photo_id"],
                        'plc_mp_app_id' => $value["anchorId"],
                        'plc_title' => $value["anchorTitle"],
                        'plc_mp_path' => $value["anchorUrl"],
                        'access_token' => $accountInfo['access_token']
                    ];
                    $kuaishouService = new KuaishouService();
                    $result = $kuaishouService->bind($bindData);
                    if ($result['code'] == 1) {
                        $ThreeVideoReleaseTask->where("photo_id", $value["photo_id"])->update([
                            'is_hand' => 2,
                        ]);
                    }
                }
                $ThreeVideoReleaseTask->where("photo_id", $value["photo_id"])->update([
                    'comment' => $arr1['video_info']["comment_count"],
                    'exposure_count' => $arr1['video_info']["comment_count"],
                    'like_count' => $arr1['video_info']["like_count"],
                ]);
            }
        }

        $taskList = $ThreeVideoReleaseTask->where($where)
            ->select()->toArray();
        return result(0, 'success', $taskList);
    }

    public function uploadShipinghaoVideo()
    {
        $ThreeVideoReleaseTask = new ThreeVideoReleaseTask();
        $taskList = $ThreeVideoReleaseTask->where(['channle_type' => 3, 'status' => 1])
            ->select()->toArray();

        if ($taskList) {
            $taskid = array_column($taskList, 'id', '');
            $ThreeVideoReleaseTask->where('id', 'in', $taskid)->update(['status' => 2]);
        }

        $FigureThreePartiesAccount = new FigureThreePartiesAccount();
        $ClipProject = new ClipProject();
        foreach ($taskList as $value) {
            $data = [];
            $accountInfo = $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])->find();
            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();
            } else {
                $apiService = new ApiService();
            }
            $clipProjctInfo = $ClipProject->where(['id' => $value['clip_project_video_id']])->find();
            $data['video'] = $clipProjctInfo['complete_video'];
            $data['cookie'] = $accountInfo['cookie'];
            $result = $apiService->uploadShipinghaoVideo($data);

            if ($result['code'] == 1 && isset($result['data']['task_id'])) {
                $ThreeVideoReleaseTask->where(['id' => $value['id']])->update(['task_id' => $result['data']['task_id'], 'status' => 5]);

            } else {
                $taskCount = $ThreeVideoReleaseTask
                    ->where(['three_video_task_id' => $value['three_video_task_id']])
                    ->where('status', 'in', [1, 2])->count();
                if ($taskCount == 0) {
                    $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])
                        ->dec('released_task')->update();
                }
                $ClipProject->where(['id' => $value['clip_project_video_id']])->update(['is_shipinghao' => 1]);
                user_balance_used($value['uid'], $value['log_no'], 3, 20);
                $ThreeVideoReleaseTask->where(['id' => $value['id']])->update([
                    'status' => 4,
                ]);
            }

        }
        echo '视频号上传成功';

    }

    public function shipinghaoVideoUploadStatus()
    {
        $ThreeVideoReleaseTask = new ThreeVideoReleaseTask();
        $taskList = $ThreeVideoReleaseTask->where(['channle_type' => 3, 'status' => 5])
            ->select()->toArray();
        $FigureThreePartiesAccount = new FigureThreePartiesAccount();
        foreach ($taskList as $value) {
            $data = [];
            $accountInfo = $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])->find();
            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();
            } else {
                $apiService = new ApiService();
            }
            $data['cookie'] = $accountInfo['cookie'];
            $data['task_id'] = $value['task_id'];
            $result = $apiService->shipinghaoVideoUploadStatus($data);
            if ($result['code'] == 1) {
                if ($result['data']['status'] == 'completed' && isset($result['data']['result']['file_path'])) {
                    $ThreeVideoReleaseTask->where(['id' => $value['id']])->update(['status' => 6]);
                }
                if ($result['data']['status'] == 'failed') {
                    $ThreeVideoReleaseTask->where(['id' => $value['id']])->update(['status' => 4]);
                    user_balance_used($value['uid'], $value['log_no'], 3, 20);
                }
            }
        }
        echo '视频号上传成功';

    }

    public function releaseShipinghaoVideo()
    {
        $ThreeVideoReleaseTask = new ThreeVideoReleaseTask();
        $taskList = $ThreeVideoReleaseTask->where(['channle_type' => 3, 'status' => 6])
            ->select()->toArray();
        $FigureThreePartiesAccount = new FigureThreePartiesAccount();
        $ClipProject = new ClipProject();
        $ThreeCopywritingModel = new ThreeCopywriting();
        $FigureAicreateModel = new FigureAicreate();
        $threeVideoTaskModel = new ThreeVideoTask();
        foreach ($taskList as $value) {


            $data = [];
            $accountInfo = $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])->find();
            $data['cookie'] = $accountInfo['cookie'];
            $data['task_id'] = $value['task_id'];
            $data['timing'] = (string)$value['release_time'];
            $liuguanIp = getliuguan($accountInfo['province_id'], $accountInfo['city_id']);
            if ($liuguanIp['code'] == 1) {
                $proxy = $liuguanIp['data']['ip'];
            } else {
                return result(-1, $liuguanIp['msg']);
            }
            $data['proxy'] = $proxy;
            $threeVideoTaskInfo = $threeVideoTaskModel->where(['id' => $value['three_video_task_id']])->find();
            if (isset($threeVideoTaskInfo['city']) ){
                $data['city'] = $threeVideoTaskInfo['city'];
            }
            $clipProjctInfo = $ClipProject->where(['id' => $value['clip_project_video_id']])->find();
            $data['thumbnail'] = $clipProjctInfo['complete_cover'];
            $data['title'] = $value['title'];
            $data['desc'] = $value['title'];;
         /*   if ($value['ai_title']) {
                $FigureAiTitleModel = new FigureAiTitle();
                $FigureAiTitleInfo = $FigureAiTitleModel->where(['id' => $value['ai_title']])->find();
                $data['title'] = $FigureAiTitleInfo['answer'];
                $data['desc'] = $FigureAiTitleInfo['answer'];;
            }*/

            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();
            } else {
                $apiService = new ApiService();
            }
            $result = $apiService->releaseShipinghaoVideo($data);

            if ($result['code'] == 1) {
                if ($result['data']['data']['baseResp']['errcode'] == 0) {
                    $ThreeVideoReleaseTask->where(['id' => $value['id']])->update(['status' => 3]);
                    $taskCount = $ThreeVideoReleaseTask
                        ->where(['three_video_task_id' => $value['three_video_task_id']])
                        ->where('status', 'in', [1, 2, 5, 6, 7])->count();
                    if ($taskCount == 0) {
                        $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])
                            ->inc('published_task')->dec('released_task')->update();
                        $threeVideoTaskModel->where(['id' => $value['three_video_task_id']])->update(['status' => 3]);
                    }

                    $ClipProject->where(['id' => $value['clip_project_video_id']])->update(['is_shipinghao' => 3]);

                    if ($clipProjctInfo['is_douyin'] == 3 &&  $clipProjctInfo['is_xiaohongshu'] ==3  &&  $clipProjctInfo['is_kuaishou'] ==3){
                        $clipProjctInfo->delete();
                    }
                } else {
                    $taskCount = $ThreeVideoReleaseTask
                        ->where(['three_video_task_id' => $value['three_video_task_id']])
                        ->where('status', 'in', [1, 2])->count();
                    if ($taskCount == 0) {
                        $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])
                            ->dec('released_task')->update();
                    }
                    $ClipProject->where(['id' => $value['clip_project_video_id']])->update(['is_shipinghao' => 1]);
                    user_balance_used($value['uid'], $value['log_no'], 3, 20);
                    $ThreeVideoReleaseTask->where(['id' => $value['id']])->update([
                        'status' => 4,
                    ]);
                }
            }
        }
        echo '视频号上传成功';

    }

    public function releaseXiaohongshuVideo()
    {
        $ThreeVideoReleaseTask = new ThreeVideoReleaseTask();
        $ThreeVideoTask = new ThreeVideoTask();
        $taskList = $ThreeVideoReleaseTask->where(['channle_type' => 4, 'status' => 1])
            ->where('release_time', '<=', time())
            ->select()->toArray();
        if ($taskList) {
            $taskid = array_column($taskList, 'id', '');
            $ThreeVideoReleaseTask->where('id', 'in', $taskid)->update(['status' => 2]);
        }
        $FigureThreePartiesAccount = new FigureThreePartiesAccount();

        $FigureAicreateModel = new FigureAicreate();
        $FigureAiTitleModel = new FigureAiTitle();
        $threeVideoTaskModel = new ThreeVideoTask();
        $ClipProject = new ClipProject();
        foreach ($taskList as $value) {
            $ThreeVideoTaskInfo = $ThreeVideoTask->where(['id' => $value['three_video_task_id']])->find();
            $data = [];
            $accountInfo = $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])->find();
            $data['cookie'] = $xiaohongshuUserInfoData['cookie'] = $accountInfo['cookie'];
            if ($ThreeVideoTaskInfo['goods_id']) {
                $data['goods_id'] = $ThreeVideoTaskInfo['goods_id'];
            }
            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();
            } else {
                $apiService = new ApiService();
            }
            $xiaohongshuUserInfo = $apiService->xiaohongshuUserInfo($xiaohongshuUserInfoData);


            if ($xiaohongshuUserInfo['code'] == 1) {
                if (isset($xiaohongshuUserInfo['data']['response_body']) && $xiaohongshuUserInfo['data']['response_body']['code'] == 0) {
                    if ($value['copywriting_id']) {
                        $FigureAicreateInfo = $FigureAicreateModel->where(['id' => $value['copywriting_id']])->find();
                        $data['desc'] = $FigureAicreateInfo['answer'];
                    }
                    if ($value['ai_title']) {

                        $FigureAiTitleInfo = $FigureAiTitleModel->where(['id' => $value['ai_title']])->find();
                        $data['title'] = $FigureAiTitleInfo['answer'];
                    }
                    $clipProjctInfo = $ClipProject->where(['id' => $value['clip_project_video_id']])->find();
                    $data['cover'] = $clipProjctInfo['complete_cover'];
                    $data['video'] = $clipProjctInfo['complete_video'];
                    $data['topic_list'] = $clipProjctInfo['topic_list'];
                    $releaseVideoInfo = $apiService->releaseXiaohongshuVideo($data);


                    if ($releaseVideoInfo['code'] == 1) {
                        if ($releaseVideoInfo['data']['code'] == 0) {
                            $ThreeVideoReleaseTask->where(['id' => $value['id']])->update([
                                'status' => 3,
                                'share_link' => $releaseVideoInfo['data']['share_link'],
                                'xiaohongshu_id' => $releaseVideoInfo['data']['data']['id'],
                            ]);
                            $taskCount = $ThreeVideoReleaseTask
                                ->where(['three_video_task_id' => $value['three_video_task_id']])
                                ->where('status', 'in', [1, 2, 5, 6, 7])->count();
                            if ($taskCount == 0) {
                                $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])
                                    ->inc('published_task')->dec('released_task')->update();
                                $threeVideoTaskModel->where(['id' => $value['three_video_task_id']])->update(['status' => 3]);
                            }
                        } else {
                            $taskCount = $ThreeVideoReleaseTask
                                ->where(['three_video_task_id' => $value['three_video_task_id']])
                                ->where('status', 'in', [1, 2])->count();
                            if ($taskCount == 0) {
                                $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])
                                    ->dec('released_task')->update();
                            }
                       //     $ClipProject->where(['id' => $value['clip_project_video_id']])->update(['is_xiaohongshu' => 1]);
                            //  user_balance_used($value['uid'], $value['log_no'], 1, 21);
                            $ThreeVideoReleaseTask->where(['id' => $value['id']])->update([
                                'status' => 4,
                            ]);
                        }
                    } else {
                        $ThreeVideoReleaseTask->where(['id' => $value['id']])->update([
                            'status' => 1,

                        ]);
                    }
                    $ClipProject->where(['id' => $value['clip_project_video_id']])->update(['is_xiaohongshu' => 3]);

                    if ($clipProjctInfo['is_douyin'] == 3 &&  $clipProjctInfo['is_shipinghao'] ==3  &&  $clipProjctInfo['is_kuaishou'] ==3){
                        $clipProjctInfo->delete();
                    }

                } else {

                    $taskCount = $ThreeVideoReleaseTask
                        ->where(['three_video_task_id' => $value['three_video_task_id']])
                        ->where('status', 'in', [1, 2])->count();

                    if ($taskCount == 0) {
                        $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])
                            ->dec('released_task')->update();
                    }
                //    $ClipProject->where(['id' => $value['clip_project_video_id']])->update(['is_xiaohongshu' => 1]);
                    //    user_balance_used($value['uid'], $value['log_no'], 1, 21);
                    $ThreeVideoReleaseTask->where(['id' => $value['id']])->update(['status' => 4]);
                    $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])->update(['status' => 2]);

                }
            } else {
                $ThreeVideoReleaseTask->where(['id' => $value['id']])->update(['status' => 1]);
            }


        }
        echo '小红书';
    }

    public function xiaohongshuVideoInfo()
    {
        $ThreeVideoReleaseTask = new ThreeVideoReleaseTask();

        $id = input('id');
        $three_account_id = input('three_account_id');
        if ($three_account_id) {
            $where['id'] = $three_account_id;
        }
        $where = ['channle_type' => 4, 'status' => 3];
        if ($id) {
            $where['id'] = $id;
        }
        /*   $taskList = $ThreeVideoReleaseTask->$where($where)
               ->select()->toArray();
           */
        $taskList = $ThreeVideoReleaseTask->where($where)
            ->where('release_time', '<=', time())
            ->select()->toArray();

        $FigureThreePartiesAccount = new FigureThreePartiesAccount();
        $threeVideoTaskModel = new ThreeVideoTask();
        $ThreeCopywritingModel = new ThreeCopywriting();
        $ThreeTitleModel = new ThreeTitle();
        $FigureAicreateModel = new FigureAicreate();
        $FigureAiTitleModel = new FigureAiTitle();
        $ClipProject = new ClipProject();
        foreach ($taskList as $value) {
            $data = [];
            $accountInfo = $FigureThreePartiesAccount->where(['id' => $value['three_account_id']])->find();
            $data['cookie'] = $xiaohongshuUserInfoData['cookie'] = $accountInfo['cookie'];
            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();
            } else {
                $apiService = new ApiService();
            }
            $xiaohongshuUserInfo = $apiService->xiaohongshuUserInfo($xiaohongshuUserInfoData);


            if ($xiaohongshuUserInfo['code'] == 1) {

                if (isset($xiaohongshuUserInfo['data']['response_body']) && $xiaohongshuUserInfo['data']['response_body']['code'] == 0)
                    $data['share_text'] = $value['share_link'];
                $data['note_id'] = $value['xiaohongshu_id'];
                $releaseVideoInfo = $apiService->xiaohongshuVideoInfo($data);

                if ($releaseVideoInfo['code'] == 1) {
                    if ($releaseVideoInfo['data']['response_body']['code'] == 0) {
                        $ThreeVideoReleaseTask->where("note_id", $value["note_id"])->update([
                            'comment' => $releaseVideoInfo['data']['response_body']['data']['items']['note_card']['comment_count'],
                            'exposure_count' => $releaseVideoInfo['data']['response_body']['data']['items']['note_card']['collected_count'],
                            'like_count' => $releaseVideoInfo['data']['response_body']['data']['items']['note_card']['interact_info']['liked_count'],
                        ]);
                    }

                }
            }
        }
        $taskList = $ThreeVideoReleaseTask->where($where)
            ->select()->toArray();
        return result(0, 'success', $taskList);
    }

    public function generate()
    {
        $video = new FigureVideo();
        $videoList = $video->where(['current_status' => 'wait_sent'])->select();

        $log = [];
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();

        } else {
            $apiService = new ApiService();
        }
        foreach ($videoList as $key => $value) {
            $videoInfo = $video->where('current_status', '=', 'init')->where(['order_number' => $value['order_number']])->find();
            if ($videoInfo) {
                continue;
            }
            if (in_array($value['order_number'], $log)) {
                continue;
            }
            $log[] = $value['order_number'];
            $video->where(['id' => $value['id']])->update([
                'current_status' => 'sent'
            ]);
            if ($value['type'] == 1) {
//                $sound = FigureCompositeSound::where([
//                    '_id' => $value['_id'],
//                ])->find();
//                if (empty($sound)) {
//                    return result(-1, 'sound不存在');
//                }
                $avatar = FigureAvatar::where([
                    'id' => $value['avatar_id']
                ])->find();
                $result = $apiService->generate([
                    'name' => $value['name'],
                    'avatar_id' => $avatar['_id'],
                    'audio_src' => $value['audio_src'],
                ]);
                if (isset($result['code']) && $result['code'] == 1) {

                    $video->where(['id' => $value['id']])->update([
                        '_id' => $result['data']['id'],
                        'current_status' => $result['data']['current_status']
                    ]);
                } else {
                    $video->where(['id' => $value['id']])->update([
                        'current_status' => 'fail'
                    ]);
                }
            } else if ($value['type'] == 2) {
                $generateData = array(
                    'name' => $value['name'],
                    'type' => 2,
                    'anchor_type' => 1,
                    'image_id' => $value['image_id'],
                    'sound_id' => $value['sound_id'],

                );
                if (!empty($value['width'])) {
                    $generateData['width'] = $value['width'];
                }
                if (!empty($value['height'])) {
                    $generateData['height'] = $value['height'];
                }
                if (!empty($value['combination'])) {
                    $generateData['combination'] = $value['combination'];
                }
                if (!empty($value['caption_json'])) {
                    $generateData['caption_json'] = $value['caption_json'];
                }
                $result = $apiService->submitVideo($generateData);


                if (isset($result['code']) && $result['code'] == 1) {

                    $video->where(['id' => $value['id']])->update([
                        '_id' => $result['data']['id'],
                        'current_status' => $result['data']['current_status']
                    ]);
                } else {
                    $video->where(['id' => $value['id']])->update([
                        'current_status' => 'fail'
                    ]);
                }
            } else if ($value['type'] == 3) {
                $generateData = array(
                    'name' => $value['name'],
                    'image_id' => $value['image_id'],
                    'sound_id' => $value['sound_id'],

                );
                if (!empty($value['width'])) {
                    $generateData['width'] = $value['width'];
                }
                if (!empty($value['height'])) {
                    $generateData['height'] = $value['height'];
                }
                if (!empty($value['combination'])) {
                    $generateData['combination'] = $value['combination'];
                }
                if (!empty($value['caption_json'])) {
                    $generateData['caption_json'] = $value['caption_json'];
                }
                $result = $apiService->generateTwo($generateData);
                if (isset($result['code']) && $result['code'] == 1) {

                    $video->where(['id' => $value['id']])->update([
                        '_id' => $result['data']['id'],
                        'current_status' => $result['data']['current_status']
                    ]);
                } else {
                    $video->where(['id' => $value['id']])->update([
                        'current_status' => 'fail'
                    ]);
                }
            } elseif ($value['type'] == 4) {
                $avatar = FigureAvatar::where([
                    'id' => $value['avatar_id']
                ])->find();
                $result = $apiService->fourGenerate([
                    'name' => $value['name'],
                    'avatar_id' => $avatar['_id'],
                    'audio_src' => $value['audio_src'],
                ]);
                if (isset($result['code']) && $result['code'] == 1) {

                    $video->where(['id' => $value['id']])->update([
                        '_id' => $result['data']['id'],
                        'current_status' => $result['data']['current_status']
                    ]);
                } else {
                    $video->where(['id' => $value['id']])->update([
                        'current_status' => 'fail'
                    ]);
                }
            }

        }
    }

    public function homepageVideo()
    {
        $homepageVideoModel = new HomepageVideo();
        $homeList = $homepageVideoModel->where(['status' => 0])->select();
        $homepageVideoModel->where(['status' => 0])->update(['status' => 2]);
        foreach ($homeList as $value) {
            $videoFileName =time().uniqid().'.mp4';
            $videoDownloadPath = root_path() . 'public/douyin' . $videoFileName;
            $ch = curl_init($value['video_url']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            $videoDataUrl = curl_exec($ch);
            curl_close($ch);
            $videoFile = fopen($videoDownloadPath, 'wb');
            fwrite($videoFile, $videoDataUrl);
            fclose($videoFile);
            $ossClient = new OssClient(sysconfig('upload', 'alioss_access_key_id'),
                sysconfig('upload', 'alioss_access_key_secret'),//'oss-cn-hangzhou.aliyuncs.com'
                sysconfig('upload', 'alioss_endpoint')
            );
            $uploadVideoUrl = $ossClient->uploadFile(sysconfig('upload', 'alioss_bucket'), $videoFileName, $videoDownloadPath);
            $ossFile = $uploadVideoUrl['info']['url'];
            unlink($videoDownloadPath);
            $homepageVideoModel->where(['id' => $value['id']])->update(['oss_url' => $ossFile,'status' => 1]);

        }
    }


    public function voiceTimerUpdate()
    {
        try {
            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();
            } else {
                $apiService = new ApiService();
            }


           $result = $apiService->voiceListUpdate(['train_mode' => 2]);

               if (isset($result['code']) && $result['code'] == 1) {

                   if (isset($result['data']) && !empty($result['data'])) {

                       $resultData = $result['data'];
                       foreach ($resultData as $kk => $vv) {
                           $voice = FigureVoiceTwin::where("_id", $vv['id'])->find();
                           if ($voice) {
                               FigureVoiceTwin::where("_id", $vv['id'])->save([
                                   'train_mode' => $vv['train_mode']
                               ]);
                           }
                       }
                   }
               } else {
                   return result(-1, $result['msg']);
               }

            /*     ;*/
            echo '声音克隆定时任务执行完成<br>';
        } catch (\Exception $e) {
            Log::error("Timer  voiceTimer:异常" . $e->getMessage() . "+++" . $e->getLine());
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    public function intelligenceTask(){
        $IntelligenceLog = new IntelligenceLog();
        $list = $IntelligenceLog->where(['status' => 0])->select();
       // $url = 'https://api.coze.cn/v1/';
        $Intelligence  = new \app\admin\model\Intelligence();

        foreach ($list as $value){
            $IntelligenceInfo  = $Intelligence->where(['id' => $value['intelligence_id']])->find();
            if ($IntelligenceInfo['authorize_type'] == 3){
                if ($IntelligenceInfo['expires_in'] < time()){
                    echo  '请求授权授权过期';exit;
                }
            }elseif($IntelligenceInfo['authorize_type'] == 2) {
                if (empty($IntelligenceInfo['api_token'])){
                    echo  '请求授权授权过期';exit;
                }
                if ( strtotime($IntelligenceInfo['api_token_expires_in']) < time() ){
                    echo  '请求授权授权过期';exit;
                }
            }else{
                $siteSet = sysconfig('site');
                if (empty($siteSet['kouzhi_token'])){
                    echo  '请求授权授权过期';exit;
                }
                if (strtotime($siteSet['kouzhi_expires_in'] )< time() ){
                    echo  '请求授权授权过期';exit;
                }
            }
            $url = 'https://api.coze.cn/v1/workflows/'.$IntelligenceInfo['work_id'].'/run_histories/'.$value['task_id'];
            if ($IntelligenceInfo['authorize_type'] == 3){
                $token = $IntelligenceInfo['token'];
            }elseif ($IntelligenceInfo['authorize_type'] == 2){
                $token = $IntelligenceInfo['api_token'];

            }else{
                $siteSet = sysconfig('site');
                if (empty($siteSet['kouzhi_token'])){
                    return result(-1, '请联系管理员,密钥未配置');
                }
                $token =$siteSet['kouzhi_token'];
            }
            $header = array(
                'Content-Type: application/json',
                'Authorization: Bearer '. $token
            );
            $ret  = $this->httpGet($url,$header);
            $result = json_decode($ret, true);


           // var_dump($result);exit;

            if ($result['code'] == 0){

                if ($result['data'][0]['execute_status'] == 'Success'){
                    $content=  json_decode($result['data'][0]['output']);;
                    $contentnew =  json_decode($content->Output);


                    $IntelligenceLog->where(['id' =>$value['id'] ])->update(
                        [
                            'output' => $contentnew->output,
                            'status' => 1
                        ]);
                }
                if ($result['data'][0]['execute_status'] == 'Fail'){
                    $IntelligenceLog->where(['id' =>$value['id'] ])->update(
                        [
                            'status' => 2
                        ]);
                }

            }
        }


    }

    function httpGet($url, $header = [])
    {
        $request = Request();
        $domain = $request->host();

        $headers = array(
            'Content-Type: application/json; charset=utf-8'
        );
        if (!empty($header)) {
            $headers = array_merge($headers, $header);
        }

        // 初始化
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        // 执行后不直接打印出来
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false); // 显示返回的Header区域内容
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // 类型为json
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 不从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        // 执行并获取HTML文档内容
        $output = curl_exec($ch);

        // 释放curl句柄
        curl_close($ch);

        return $output;
    }


}